
#include <logger.hpp>

#include "io_service_pool_impl.hpp"
#include "session.hpp"
#include "session_manager.hpp"

using namespace xbase;

typedef boost::system::error_code error_code;

void handle_connect(bool to_close,
		    session_ptr s,
		    const boost::system::error_code &ec)
{
	if(ec)
	{
		std::cout << "handle_connect : " << ec.message() << std::endl;
		return;
	}

	if(s->socket().is_open())
	{
		std::cout << "got session < "
			  << s->socket().local_endpoint() << " --> "
			  << s->socket().remote_endpoint()
			  << " >" << std::endl;

		if(to_close)
			s->close();
	}
	else
	{
		std::cout << "got closed session" << std::endl;
	}
}

void handle_connect_2(session_ptr s,
		      const boost::system::error_code &ec)
{
	handle_connect(false, s, ec);
}  


int main(int argc, char **argv)
{
	LOG_CONFIG("../../conf/log4cplus.tablet_server.conf");
	
	if(!((4 <= argc) && (argc <= 5))) // argc - [4, 5]
	{
		std::cout << "test_session_manager <ip> <port> <times> [close on connected]" << std::endl;
		return 0;
	}

	const int times = ::atoi(argv[3]);
	boost::asio::ip::tcp::endpoint endpoint(
		boost::asio::ip::address::from_string(argv[1]),
		::atoi(argv[2])
		);

	bool to_close = false;
	if(argc >= 5)
		to_close = (std::string("true") == argv[4] ? true : false);

	//
	// 首先初始化service_pool并启动
	// 

	boost::shared_ptr<io_service_pool> pool(new impl::single_io_service());
	client_options options;
	pool->set_options(options);
	pool->run();

	// 执行异步操作

	session_manager sm(*pool);
	
	for(int i=0; i<times; ++i)
	{
		sm.async_connect(endpoint,
				 boost::bind(handle_connect, to_close, _1, _2));
	}

	// 结束

	std::string input;
	while(std::cin >> input)
	{
		if(input == "close")
		{
			sm.close();
		}
		else if(input == "quit")
		{
			break;
		}
	}

	pool->stop();
	pool->join();

	return 0;
}

